package a10_动态规划;

/**
 * <p>
 * a53_最长回文子序列复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/4/1
 */
public class a53_最长回文子序列复习2 {
    public static void main(String[] args) {
        System.out.println(longestPalindromeSubseq("bbbab"));
    }
    //dp[i][j]：代表从i到j的最长回文子序列为dp[i][j]

    //递推公式：
    //if(chars[i] == chars[j]){
    //  dp[i][j] = dp[i+1][j-1] + 2;
    //}else{
    //   dp[i][j] = Math.max(dp[i][j-1],dp[i+1][j]);
    //}

    //初始化：
    //初始化i==j的时候
    //dp[i][j] == 1

    //遍历顺序：来自于左和左下角和下
    //从下到上，从左往右
    public static int longestPalindromeSubseq(String s) {
        char[] chars = s.toCharArray();
        int[][] dp = new int[chars.length][chars.length];

        for (int i = 0; i < chars.length; i++) {
            dp[i][i] = 1;
        }

        for (int i = chars.length - 1; i >= 0; i--) {
            for (int j = i + 1; j < chars.length; j++) {
                if(chars[i] == chars[j]){
                    dp[i][j] = dp[i+1][j-1] + 2;
                }else {
                    dp[i][j] = Math.max(dp[i][j-1],dp[i+1][j]);
                }
            }
        }
        return dp[0][chars.length-1];
    }
}
